cc.Class({
    extends: cc.Component,

    properties: {
        lblRoomNo:{
            default:null,
            type:cc.Label
        },
        _seats:[],
        _seats2:[],
        _timeLabel:null,
        _dayLabel:null,
        _voiceMsgQueue:[],
        _lastPlayingSeat:null,
        _playingSeat:null,
        _lastPlayTime:null,
    },

    // use this for initialization
    onLoad: function () {
        if(cc.vv == null){
            return;
        }
        
        this.initView();
        this.initSeats();
        this.initEventHandlers();
    },
    
    initView:function(){

        // 准许页面的桌面信息
        var prepare = this.node.getChildByName("prepare");
        var seats = prepare.getChildByName("seats");
        for(var i = 0; i < seats.children.length; ++i){

            //修改成二人
            if(cc.vv.setPeople.hide_single(i)){
                // cc.log("MJRoom","hide i="+i);
                continue;
            }
            this._seats.push(seats.children[i].getComponent("Seat"));
        }
        
        this.refreshBtns();
        
        this.lblRoomNo = cc.find("Canvas/infobar/Z_room_txt/New Label").getComponent(cc.Label);
        this._timeLabel = cc.find("Canvas/infobar/time").getComponent(cc.Label);
        this._dayLabel = cc.find("Canvas/infobar/day").getComponent(cc.Label);

        this.lblRoomNo.string = cc.vv.gameNetMgr.roomId;

        //game 页面信息
        var gameChild = this.node.getChildByName("game");
        var sides = ["myself","right","up","left"];
        for(var i = 0; i < sides.length; ++i){
            var sideNode = gameChild.getChildByName(sides[i]);
            var seat = sideNode.getChildByName("seat");

            //修改成二人
            if(cc.vv.setPeople.hide_single(i)){
                // cc.log("MJRoom","hide i="+i);
                continue;
            }
            this._seats2.push(seat.getComponent("Seat"));
        }
        
        var btnWechat = cc.find("Canvas/prepare/btnWeichat");
        if(btnWechat){
            cc.vv.utils.addClickEvent(btnWechat,this.node,"MJRoom","onBtnWeichatClicked");
        }       
        
        if(cc.vv.gameNetMgr.isInitZhuang)
        {
            console.log("initZhuang of MJRoom.js");
            cc.vv.gameNetMgr.dispatchEvent('initZhuang',cc.vv.gameNetMgr.button);
        }
    },
    
    refreshBtns:function(){
        var prepare = this.node.getChildByName("prepare");
        var btnExit = prepare.getChildByName("btnExit");
        var btnDispress = prepare.getChildByName("btnDissolve");
        var btnWeichat = prepare.getChildByName("btnWeichat");
        var btnBack = prepare.getChildByName("btnBack");
        var isIdle = cc.vv.gameNetMgr.numOfGames == 0;
        
        btnExit.active = !cc.vv.gameNetMgr.isOwner() && isIdle;
        // console.log(btnExit.active);
        btnDispress.active = cc.vv.gameNetMgr.isOwner() && isIdle;
        
        btnWeichat.active = isIdle;
        btnBack.active = isIdle;
    },
    
    initEventHandlers:function(){
        var self = this;
        this.node.on('new_user',function(data){
            console.log("new_user of MJRoom"+data.detail);
            self.initSingleSeat(data.detail);
        });
        
        this.node.on('user_state_changed',function(data){
            console.log("user_state_changed of MJRoom"+data.detail);
            self.initSingleSeat(data.detail);
        });
        this.node.on('user_state_changedicon',function(data){
            console.log("user_state_changedicon of MJRoom"+data.detail);
            self.initSingleSeat(data.detail,true);
        });
        this.node.on('game_begin',function(data){
            console.log("game_begin of MJRoom");
            self.refreshBtns();
            self.initSeats();
            // cc.vv.
        });

        this.node.on('initZhuang',function(data){
            console.log("initZhuang of MJRoom type="+data.detail );
            self.initZhuang(data.detail);
        });
        
        this.node.on('game_num',function(data){
            self.refreshBtns();
        });

       this.node.on('game_over',function(data){
            self.refreshBtns();
        });

        //主要是同步后，刷新头像信息。不包括买/顶
        this.node.on('refresh_sync_infs',function(data) {
            self.initSeats();
            // if(cc.vv.gameNetMgr.gamestate=='playing') {
            //     self
            // }
        });

        this.node.on('refresh_sync_ready_infs',function(data) {
            console.log('refresh_sync_ready_infs');
            self.initSeats();
        });
        
        this.node.on('voice_msg',function(data){
            var data = data.detail;
            self._voiceMsgQueue.push(data);
            self.playVoice();
        });
        
        this.node.on('chat_push',function(data){
            var data = data.detail;
            var idx = cc.vv.gameNetMgr.getSeatIndexByID(data.sender);
            var localIdx = cc.vv.gameNetMgr.getLocalIndex(idx);

            if(self.isActive("prepare")){
                self._seats[localIdx].chat(data.content);
            }
            if(self.isActive("game")){
               self._seats2[localIdx].chat(data.content);
            }
        });
        
        this.node.on('quick_chat_push',function(data){
            console.log("quick_chat_push");
            console.log(data);
            var data = data.detail;
            var idx = cc.vv.gameNetMgr.getSeatIndexByID(data.sender);
            var localIdx = cc.vv.gameNetMgr.getLocalIndex(idx);
            var index = data.content;
            var info = cc.vv.chat.getQuickChatInfo(index);
            if(self.isActive("prepare")){
                self._seats[localIdx].chat(info.content);
            }
            if(self.isActive("game")){
                self._seats2[localIdx].chat(info.content);
            }
            cc.vv.audioMgr.playSFX(info.sound);
        });
        
        this.node.on('emoji_push',function(data){
            var data = data.detail;
            var idx = cc.vv.gameNetMgr.getSeatIndexByID(data.sender);
            var localIdx = cc.vv.gameNetMgr.getLocalIndex(idx);
            // console.log(data);
            if(self.isActive("prepare")){
                self._seats[localIdx].emoji(data.content);
            }
            if(self.isActive("game")){
                self._seats2[localIdx].emoji(data.content);
            }
        });
    },

    isActive:function(name){
        var temp=this.node.getChildByName(name);
        // cc.log("isActive of",temp);
        if(temp){
            return temp.active;
        }
        return false;
    },
    
    initSeats:function(){
        var seats = cc.vv.gameNetMgr.seats;
        cc.log("seat.length="+seats.length);
        if(!seats){
            console.log("initSeats is failed of MJRoom");
            return;
        }
        for(var i = 0; i < seats.length; ++i){
            this.initSingleSeat(seats[i]);
        }
    },
    
    initSingleSeat:function(seat,type){
        var index = cc.vv.gameNetMgr.getLocalIndex(seat.seatindex);
        // cc.log("initSingleSeat of index="+index,seat.seatindex);
        var isOffline = !seat.online;
        var isZhuang = seat.seatindex == cc.vv.gameNetMgr.button;
        
        // console.log("isOffline:" + isOffline);
        this._seats[index].setInfo(seat.name,seat.score);
        this._seats[index].setReady(seat.ready);
        this._seats[index].setOffline(isOffline);
        this._seats[index].setID(seat.userid);
        this._seats[index].voiceMsg(false);
        if(type)
        {
            this._seats[index].seticon();
        }
        this._seats2[index].setInfo(seat.name,seat.score);

        // this._seats2[index].setZhuang(isZhuang);
        // if(!isZhuang)
        // {
        //     var number = seat.seatindex-cc.vv.gameNetMgr.button;
        //     // cc.log("initSingleSeat number="+number,);
        //     if(cc.vv.setPeople.isERMJ()){//修改成二人
        //         number=2;
        //     }
        //     this._seats2[index].setweizhi(number);
        // }
        if(cc.vv.gameNetMgr.button == -1)
        {
            this._seats2[index].setweizhi(100);
        }
        this._seats2[index].setOffline(isOffline);
        this._seats2[index].setID(seat.userid);
        this._seats2[index].voiceMsg(false);
    },

    initZhuang:function(index)
    {
        cc.log("initZhuang",index);
        //如果是二人的话，button只能是0,1
        var seat = cc.vv.gameNetMgr.getLocalIndex(index);
        console.log(seat);
        console.log(this._seats2[seat]);
        this._seats2[seat].setZhuang(true);

        if(cc.vv.setPeople.isERMJ()){
             var seat = cc.vv.gameNetMgr.getLocalIndex(index+1);
            this._seats2[seat].setweizhi(2);
            return;
        }
        for(var i = 1;i<4;i++)
        {
            var seat = cc.vv.gameNetMgr.getLocalIndex(index+i);
            this._seats2[seat].setweizhi(i);
        }    
    },
    
    onBtnSettingsClicked:function(){
        console.log("onBtnSettingsClicked of MJRoom.js");
        cc.vv.popupMgr.showSettings();   
    },

    onBtnBackClicked:function(){
        cc.vv.alert.show("返回大厅","返回大厅房间仍会保留，快去邀请大伙来玩吧！",function(){
            cc.director.loadScene("hall");    
        },true);
    },
    
    onBtnChatClicked:function(){
        
    },
    
    onBtnWeichatClicked:function(){
        var title = "4人";
        if(cc.vv.gameNetMgr.conf.type == "wzer"){
            title = "2人";
        }
        var str = "";
        if(cc.vv.gameNetMgr.dishu == 1)
        {
            str = "2468";
        }
        else if(cc.vv.gameNetMgr.dishu == 2)
        {
            str = "无进阶底";
        }
        else
        {
            console.log("wanfa label erro!");
            return;
        }
        // cc.vv.anysdkMgr.share("有朋温州麻将" + title,"房号:" + cc.vv.gameNetMgr.roomId + " 玩法:" + cc.vv.gameNetMgr.getWanfa());
        cc.vv.anysdkMgr.share("有朋温州麻将","房号:" + cc.vv.gameNetMgr.roomId+" \n房间规则："+title+", " + cc.vv.gameNetMgr.maxNumOfGames + "局  \n底分 1 , 进阶底数" + str,true);

    },
    
    onBtnDissolveClicked:function(){
        cc.vv.alert.show("解散房间","解散房间不扣房卡，是否确定解散？",function(){
            cc.vv.net.send("dispress");    
        },true);
    },
    
    onBtnExit:function(){
        cc.vv.net.send("exit");
    },
    
    playVoice:function(){
        if(this._playingSeat == null && this._voiceMsgQueue.length){
            console.log("playVoice2");
            var data = this._voiceMsgQueue.shift();
            var idx = cc.vv.gameNetMgr.getSeatIndexByID(data.sender);
            var localIndex = cc.vv.gameNetMgr.getLocalIndex(idx);
            this._playingSeat = localIndex;
            this._seats[localIndex].voiceMsg(true);
            this._seats2[localIndex].voiceMsg(true);
            
            var msgInfo = JSON.parse(data.content);
            
            var msgfile = "voicemsg.amr";
            console.log(msgInfo.msg.length);
            cc.vv.voiceMgr.writeVoice(msgfile,msgInfo.msg);
            cc.vv.voiceMgr.play(msgfile);
            this._lastPlayTime = Date.now() + msgInfo.time;
        }
    },
    
    // called every frame, uncomment this function to activate update callback
    update: function (dt) {
        var minutes = Math.floor(Date.now()/1000/60);//获取当前时间
        if(this._lastMinute != minutes){
            this._lastMinute = minutes;
            var date = new Date();
            var h = date.getHours();
            h = h < 10? "0"+h:h;
            
            var m = date.getMinutes();
            m = m < 10? "0"+m:m;
            this._timeLabel.string = "" + h + ":" + m;  
            // var dayDate=Data.now(); 
            var dateNow=Date.now();
            var dayDate= new Date(dateNow);
            var month=dayDate.getMonth()+1;
            // console.log();
            month=month<10?"0"+month:month;
            var day=dayDate.getDate();
            day=day<10?"0"+day:day;
            // console.log("---------------day &month="+day+" "+month);
            this._dayLabel.string=month+"/"+day;
        }
        
        
        if(this._lastPlayTime != null){
            if(Date.now() > this._lastPlayTime + 200){
                this.onPlayerOver();
                this._lastPlayTime = null;    
            }
        }
        else{
            this.playVoice();
        }
    },
    
        
    onPlayerOver:function(){
        cc.vv.audioMgr.resumeAll();
        console.log("onPlayCallback:" + this._playingSeat);
        var localIndex = this._playingSeat;
        this._playingSeat = null;
        this._seats[localIndex].voiceMsg(false);
        this._seats2[localIndex].voiceMsg(false);
    },
    
    onDestroy:function(){
        cc.vv.voiceMgr.stop();
//        cc.vv.voiceMgr.onPlayCallback = null;
    }
});
